import time
from PIL import ImageGrab
from PIL import Image
from pynput.mouse import Controller as MController, Button as MButton
from pynput.keyboard import Key as KBKey, Controller as KBController

keyboard = KBController()
mouse = MController()

# 静静等待
time.sleep(5)

"""
(0,0)                 ┬
                      |
                     72
                      |
                      ┴
                 ├-20-┤
├---------136---------┤├------------------677------------------┤├-20-┤
                      .
					  .
					  .
					  
					                                                      (959,1035)

"""
# 头部高度
bannerHeight = 72
# 文章宽度
articleWidth = 677
# 截图区域
xStart = 0
xEnd = 960
yStart = 0 + bannerHeight
yEnd = 1036
print("capture area:(%4d, %4d) - (%4d, %4d)"% (xStart, yStart, xEnd, yEnd))
# 文章预留左右侧宽度
articleXMargin = 130
# 文章左侧的X轴起点坐标
articleXStart = 136
# 文章区域
articleWrapperXStart = xStart + articleXStart - articleXMargin
articleWrapperXEnd = articleXStart + articleWidth + articleXMargin
articleWrapperYStart = yStart
articleWrapperYEnd = yEnd
print("article area:(%4d, %4d) - (%4d, %4d)"% (articleWrapperXStart, articleWrapperYStart, articleWrapperXEnd, articleWrapperYEnd))



def imageCompare(image1, image2, compareHeight):
	"图片比较"
	if image1.width != image2.width or image1.height != image2.height:
		return False
	
	else:
		for x in range(0, image1.width):
			for y in range(image1.height - compareHeight, image1.height):
				if image1.getpixel((x, y)) != image2.getpixel((x, y)):
					return False
	return True
	
	
def imageMerge(images):
	"图片合并"
	# 垂直比较的高度
	compareHeight = 20
	width = images[0].width;
	
	for i in range(1, len(images)):
		imageT = images[i - 1]
		imageB = images[i]
		imageTLast20 = imageT.crop((0, imageT.height - compareHeight, imageT.width, imageT.height))
		
		for j in range(0, imageB.height - compareHeight):
			imageB20 = imageB.crop((0, j, imageB.width, j + compareHeight))
			if imageCompare(imageTLast20, imageB20, compareHeight):
				images[i] = imageB.crop((0, j + 20, imageB.width, imageB.height));
				break
	# 计算出总高度
	finalImageHeight = 0
	for i in range(0, len(images)):
		finalImageHeight += images[i].height
	# 创建图片
	finalImage = Image.new("RGB", (width, finalImageHeight), "white")
	# 当前高度
	height = 0
	for i in range(0, len(images)):
		image = images[i]
		# 合并到FinalImage图片
		finalImage.paste(image, (0, height))
		height += image.height
	
	return finalImage
		

def grabArticle(name):
	"抓取文章"
	ims = []
	imLen = 0
	# 文章可能没有停留在最上方
	# 需要按下HOME
	keyboard.press(KBKey.home)
	keyboard.release(KBKey.home)
	time.sleep(2)
	
	ims = []
	imLen = 0
	for i in range(0, 100):
		# 最大滚动100次
		ims.append(ImageGrab.grab((articleWrapperXStart, articleWrapperYStart, articleWrapperXEnd, articleWrapperYEnd)))
		imLen += 1
		if imLen > 1:
			if imageCompare(ims[imLen - 1] , ims[imLen - 2], 200):
				break
		# 8 steps and wait for 3 seconds
		mouse.scroll(0, -8)
		time.sleep(3)

	
	ims.pop()
	imLen -= 1
	print("%d images generated."%(imLen))

	finalImage = imageMerge(ims)
	finalImage.save("C:\\capture\\articles\\%s.png"%(name))


# 分隔行判定区域
splitStart = 2
splitEnd = 5
splitColor = (242, 242, 243)
# 循环抓取
for i in range(0, 1000):

	# 打开文章列表
	print("\n\n抓取第%04d篇文章"%(i))
	print("move to (%d, %d), click the article."%(1448, 117))
	mouse.position = (1448, 117)
	mouse.click(MButton.left, 1)
	time.sleep(2)
	print("move to (%d, %d), click the article."%(1645, 325))
	mouse.position = (1645, 325)
	mouse.click(MButton.left, 1)
	time.sleep(10)
	# 
	print("move to (%d, %d), click the article."%(xStart + 50, 20))
	mouse.position = (xStart + 50, 20)
	mouse.click(MButton.left, 1)
	time.sleep(1)
	mouse.position = (xStart + 50, yStart + 50)

	# 文章可能没有停留在最上方
	# 需要按下HOME
	keyboard.press(KBKey.home)
	keyboard.release(KBKey.home)
	time.sleep(2)
	for j in range(i + 2):
		mouse.scroll(0, -1)
		time.sleep(3)
		
	# 抓取屏幕指定区域
	im = ImageGrab.grab((xStart, yStart, xEnd, yEnd))
	# 找出分隔行Y轴坐标
	splitYs = []
	for line in range(0, yEnd):
		if im.getpixel((2, line)) == splitColor and im.getpixel((3, line)) == splitColor and im.getpixel((4, line)) == splitColor:
			# 点击文章
			print("move to (%d, %d), click the article."%(xStart + 50, line + yStart + 50))
			mouse.position = (xStart + 50, line + yStart + 50)
			mouse.click(MButton.left, 1)
			time.sleep(10)
			# 抓取文章
			grabArticle("%04d"%(i))
			# 点击返回列表
			print("move to (%d, %d), click the back button."%(xStart + 38, yStart - 2))
			mouse.position = (xStart + 38, yStart - 20)
			mouse.click(MButton.left, 1)
			time.sleep(10)
			mouse.position = (xStart + 38, yStart + 20)
			mouse.click(MButton.left, 1)
			time.sleep(2)
			break
			
